package com.zxc.shortlink.core;

import com.zxc.shortlink.consts.StrategyConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;

/**
* @author zxc_user
* @date 2022/3/24 17:06
* @version 1.0
* @description redis生成策略
**/
@Primary
@Service(value = StrategyConst.SHORT_BUILD_REDIS)
@Slf4j
public class RedisShortLinkBuildStrategy implements ShortLinkBuildStrategy {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String REDIS_SHORT_LINK = "REDIS_SHORT_LINK_";
    private static final Integer REDIS_SHORT_LINK_EXPIRE_HOUR = 24;

    @Override
    public String build() {
        String today = LocalDate.now().toString().replace("-", "");
        String todayString = REDIS_SHORT_LINK.concat(today);
        redisTemplate.opsForValue().setIfAbsent(todayString, "-1", Duration.ofHours(REDIS_SHORT_LINK_EXPIRE_HOUR));
        String result = today + redisTemplate.opsForValue().increment(todayString);
        log.info("生成短链接的数据为{}", result);
        return result;
    }

}
